#!/usr/bin/env elixir

defmodule FakeCEC do
  def start(_) do
    IO.puts "log level set to 8"
    IO.puts "log level set to 8"
    IO.puts "No device type given. Using 'recording device'"
    IO.puts "CEC Parser created - libCEC version 3.0.1"
    IO.puts "no serial port given. trying autodetect:"
    IO.puts " path:     Raspberry Pi"
    IO.puts "  com port: RPI"
    IO.puts ""
    IO.puts "  opening a connection to the CEC adapter..."

    traffic_out("e0")
    traffic_out("e0:8c")
    traffic_in("0f:87:00:00:f0")
    traffic_out("11")
    traffic_out("11")
    traffic_out("1f:84:34:00:01")
    traffic_out("10:47:43:45:43:54:65:73:74:65:72")
    traffic_out("10:8f")
  end

  def traffic_out(code) do
    IO.puts "  TRAFFIC: [                1]  << #{code}"
  end

  def traffic_in(code) do
    IO.puts "  TRAFFIC: [                1]  >> #{code}"
  end

  def process_code(code) do
    traffic_out(code)
    respond(code)
  end

  def respond(code) when code == "15:71" do
    :timer.sleep(10)
    traffic_out("51:7A:32")
  end

  def respond(_code) do
    nil
  end

  def process(state, input) do
    case input do
      :eof -> nil
      {:error, :terminated} -> (
        System.halt(0)
      )
      str -> case Regex.run(~r/tx\s(.+)$/, str) do
        [_, code] -> process_code(code)
        _ -> nil
      end
    end

    process(state, IO.gets "waiting for input\n")
  end
end

state = %{
  tv: %{
    power_on: true
  }
}

FakeCEC.start(state)
|> FakeCEC.process(IO.gets "waiting for input\n")
